import { useState, useCallback, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from 'react-router-dom';
import CompanyService from "../../app/services/companyService";
import { showNotification } from "../common/headerSlice";
import Pagination from "../../components/Pagination";
import PencilIcon from "@heroicons/react/24/outline/PencilIcon";
import CommonService from "../../app/services/commonService";
import PlusIcon from "@heroicons/react/24/outline/PlusIcon";
import ConfirmDialog from "../../components/ConfirmDialog";
import TitleCard from "../../components/Cards/TitleCard";
import { NotificationManager } from "react-notifications";
import _ from "lodash";

function Departments() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [data, setData] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [total, setTotal] = useState(0);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [selectedId, setSelectedId] = useState(0);

  const fetchData = useCallback(() => {
    CommonService.setLoading(true);
    CompanyService.list(pageIndex).then((res) => {
      if (res.success) {
        setData(res.data);
        setTotal(res.total);
      } else {
        dispatch(
          showNotification({
            message: "获取数据失败",
            status: "error",
          })
        );
      }
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }, [pageIndex]);

  useEffect(() => {
    fetchData();
  }, [pageIndex]);

  const onPageChange = (pageIndex) => {
    setPageIndex(pageIndex);
  }

  const editCompany = (id) => {
    navigate(`/app/departments/edit/${id}`);
  }

  const removeCompany = (id) => {
    const company = _.find(data, { id: id });
    if (company == null) return;
    setSelectedId(id);
    setShowConfirmDialog(true);
  }
  const onCancel = () => {
    setShowConfirmDialog(false);
    setSelectedId(0);
  }
  const onSuccess = () => {
    CompanyService.remove(selectedId).then((res) => {
      if (res.success) {
        NotificationManager.success("删除成功", '提示');
        fetchData();
        setSelectedId(0);
      } else {
        NotificationManager.success("删除失败", '提示');
      }
    });
  }

  return (
    <>
      <ConfirmDialog title="提示" showModel={showConfirmDialog} onCancel={onCancel} onSuccess={onSuccess}><div className=" text-sm">确认删除机构?</div></ConfirmDialog>
          <div className="flex flex-col">
            <TitleCard title="机构管理" topMargin="mt-2" TopSideButtons={
                (<div className="inline-block"><button className="btn btn-sm bg-primary text-white"  onClick={() => navigate("/app/departments/edit/0")}><PlusIcon className="w-4 h-4" />新增机构</button></div>)} >
            <table className="table table-zebra bg-base-100 rounded-sm  border-1">
              <thead>
                <tr className=" border-b-2 border-base-100">
                  <th  className=" text-center">序号</th>
                  <th  className=" text-center">组织名称</th>
                  <th  className=" text-center">组织联系人</th>
                  <th  className=" text-center">联系人电话</th>
                  <th  className=" text-center">联系地址</th>
                  <th  className=" text-center">状态</th>
                  <th  className=" text-center">操作</th>
                </tr>
              </thead>
              <tbody>
                {data && data.length > 0 ? (
                  data.map((item, index) => {
                    return (
                      <tr key={index}>
                        <th  className=" text-center">{item.id}</th>
                        <td className=" text-center">{item.companyName}</td>
                        <td className=" text-center">{item.contactName}</td>
                        <td className=" text-center">{item.contactPhone}</td>
                        <td className=" text-center">{item.companyAddress}</td>
                        <td className=" text-center">{item.status === 1 ? "正常" : "禁用"}</td>
                        <td className=" text-center">
                          <div className="flex flex-row items-center justify-around ">
                            <button className="btn btn-sm text-green-500 btn-link" onClick={() => editCompany(item.id)}><PencilIcon className="w-4 h-4" />  编辑</button>
                            {/* <button className="btn btn-sm text-red-500 btn-link"  onClick={() => removeCompany(item.id)}><TrashIcon className="w-4 h-4" />删除</button> */}
                          </div>
                        </td>
                      </tr>
                    );
                  })
                ) : (
                  <tr>
                    <td colSpan="7">暂无数据</td>
                  </tr>
                )}
              </tbody>
            </table>
            <div className="flex flex-row items-center justify-center">
              <Pagination currentPage={pageIndex} totalCount={total} onPageChange={onPageChange} />
            </div>
            </TitleCard>
          </div>
    </>
  );
}

export default Departments;
